import requests
import time
import flask


def send(text, roomid):
    url = 'https://api.live.bilibili.com/msg/send'
    data = {
        'bubble': '0',
        'msg': text,
        'color': '16777215',
        'mode': '1',
        'room_type': '0',
        'jumpfrom': '77002',
        'fontsize': '25',
        'rnd': str(int(time.time())),           # 这个是时间戳    '1685423782'
        'roomid': roomid,
        'csrf': '0482a349159efb7792558f0d40a9da4d',
        'csrf_token': '0482a349159efb7792558f0d40a9da4d'
            }
    header = {
            'cookie': "buvid3=86686956-91ED-F38F-00CC-3E59AEEDD8F910438infoc; i-wanna-go-back=-1; _uuid=D78108BA1-E8CD-9659-951C-6E79F7489BB210572infoc; FEED_LIVE_VERSION=V8; home_feed_column=5; buvid_fp=82480fb1e6ef05eff922bd969a046be7; nostalgia_conf=-1; CURRENT_FNVAL=4048; rpdid=|(u|u))J|u~u0J'uY)J~mYYRY; DedeUserID=489537957; DedeUserID__ckMd5=70645e4746a802c2; CURRENT_QUALITY=80; b_ut=5; header_theme_version=CLOSE; LIVE_BUVID=AUTO5516847218574582; b_nut=1684723309; browser_resolution=1865-968; Hm_lvt_8a6e55dbd2870f0f5bc9194cddf32a02=1685410404,1685609036,1685677026; innersign=0; SESSDATA=b68e8069%2C1701481427%2C6ab08%2A62; bili_jct=0482a349159efb7792558f0d40a9da4d; sid=5d07r826; bp_video_offset_489537957=803267980821528600; b_lsid=6E693753_1888A0FCDD7; buvid4=266D2AB5-0C5E-41E4-E398-AEDAC6B625F411119-023051117-qGKWoYopdiF3gtJd/6YQlQ%3D%3D; _dfcaptcha=5796ec0092009025fc2176ded9886f03; PVID=7"
    }
    # response = requests.post(url,data=data,headers=header).text

    max_attempts = 3  # 最大重试次数
    wait_time = 1  # 重试间隔时间（秒）

    for attempts in range(max_attempts):
        try:
            response = requests.post(url, data=data, headers=header)
            response.raise_for_status() # 检查响应状态码，如果不是200，会抛出异常
            return response.text  # 发送成功，返回响应结果
        except requests.exceptions.RequestException as e:
            print(f"错误原因: {str(e)}")
            if attempts < max_attempts - 1:
                print(f"等待 {wait_time} 秒...")
                time.sleep(wait_time)

    print("Failed to send danmu after multiple attempts.")
    return None


def barrage(roomid):
    url = "http://api.live.bilibili.com/ajax/msg?roomid="
    res = requests.get(url + roomid).json()
    res = res['data']['room'][-1]
    print(res)

if __name__ == '__main__':
    roomid = "68519"
    text = 'heihei'
    send(text , roomid)